package com.example.pingapplication2.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;

public class Ping {
    public String net = "NO_CONNECTION";
    public String host = "";
    public String ip = "";
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
    public boolean isSuccessful = false;

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//ConnectivityManager功能：监视网络连接状态
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();// 获取正连接的网络的信息
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public static Ping ping(URL url, Context ctx) {
        Ping r = new Ping();
        Socket socket = new Socket();
        if (isNetworkConnected(ctx)) {
            r.net = getNetworkType(ctx);
            //Log.d("NetworkType", r.net);
            try {
                String hostAddress;
                long start = System.currentTimeMillis();
                //url.getHost():
                //String url = "https://www.baidu.com";
                //URL urls = new URL(url);
                //System.out.println(urls.getHost());
                //返回：www.baidu.com
                //但是如果String url = "www.baidu.com";
                //抛出异常：Exception in thread "main" java.net.MalformedURLException: no protocol: www.baidu.com
                //String hostAddress = InetAddress.getByName(urls.getHost()).getHostAddress();
                //返回182.61.200.6
                //Log.d("url.getHost()",url.getHost());
                //这一步必须联网才行，不然会异常
                hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
                //Log.d("hostAddress", hostAddress);
                long dnsResolved = System.currentTimeMillis();//获取当前时间，以ms来计
                //System.out.println(urls.getPort());
                //返回-1
                //InetAddress:主要作用是封装IP及DNS
                //InetSocketAddress：主要作用是封装端口 他是在在InetAddress基础上加端口
                SocketAddress socketAddress = new InetSocketAddress(hostAddress, url.getPort());
                //Log.d("到达","socket.connect");
                socket.connect(socketAddress, 200);//0.2 毫秒的超时连接，如果没有连接上说明失败了
                socket.close();
                long probeFinish = System.currentTimeMillis();
                r.dns = (int) (dnsResolved - start);
                r.cnt = (int) (probeFinish - dnsResolved);
                Log.d("链接的时间",String.valueOf(r.cnt));
                r.host = url.getHost();
                r.ip = hostAddress;

                //Log.d("PingTest", "success");
                r.isSuccessful = true;
            } catch (Exception ex) {
                r.isSuccessful = false;
                //Log.d("PingTest", " fail");
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            Log.d("网络服务", "未连接！ ");
        }
        return r;
    }

    public static String getNetworkType(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            return activeNetwork.getTypeName();
        }
        return null;
    }

    @Override
    public String toString() {
        return net + host + ip + dns + cnt + isSuccessful;
    }
}
